<?php
namespace app\common\controller;
use think\Loader;
use think\Controller;
use think\Session;
use app\spadmin\library\Auth;

class Backend extends Controller
{
    protected $model;
    protected $auth;

    use \app\spadmin\library\traits\backend;

    public function _initialize()
    {
        $modulename = $this->request->module();
        $controllername = Loader::parseName($this->request->controller());
        $actionname = strtolower($this->request->action());
        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        $this->auth = Auth::instance();
        $this->auth->setRequestUri($path);
        //不需要登录的url
        $noLoginUrl = $this->auth->getNologinRole();
        if(!in_array($path,$noLoginUrl)){
            //检测是否登录
            if (!$this->auth->isLogin()) {
                $url = Session::get('referer');
                if (in_array($this->request->pathinfo(), ['/', 'index/index'])) {
                    $this->redirect('index/login', [], 302, ['referer' => '']);
                    exit;
                }
                if($actionname == 'index'){
                    $url =  $this->request->url();
                    $this->redirect('index/login', [], 302, ['referer' => $url]);
                    exit();
                }
                $this->error('登录失效，请重新登陆',url('index/login'));
            }
            //不需要权限的url
            $noauthUrl = $this->auth->getNoAuthRole();
            if(!in_array($path,$noauthUrl)){
                // 判断控制器和方法是否有对应权限
                if (!$this->auth->check($path)) {
                    $this->error('无权访问', '');
                }
            }
        }else{
            if($path == 'index/login' && $this->auth->isLogin()){
                $url = Session::get('referer');
                $this->redirect('index/index', [], 200, ['referer' => $url]);
            }
        }
        

    }


}